package com.sdy.supermarket.web.controller.admin;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sdy.auth.api.model.UserInfo;
import com.sdy.auth.client.service.SsoService;
import com.sdy.common.model.BizException;
import com.sdy.common.model.Response;
import com.sdy.common.utils.Assert;
import com.sdy.common.utils.StringUtil;
import com.sdy.mvc.controller.BaseController;
import com.sdy.supermarket.biz.model.GsApproveFlow;
import com.sdy.supermarket.biz.model.GsOrderItem;
import com.sdy.supermarket.biz.model.GsRes;
import com.sdy.supermarket.biz.model.GsResIntention;
import com.sdy.supermarket.biz.model.GsResIntentionRemark;
import com.sdy.supermarket.biz.param.ApproveFlowParam;
import com.sdy.supermarket.biz.service.*;
import com.sdy.supermarket.biz.utils.DeCodeUtil;
import com.sdy.supermarket.biz.vo.*;
import com.sdy.usercenter.api.UserQueryApi;
import com.sdy.usercenter.api.dto.DeptDto;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;

/**
 * 管理员后台
 *
 * @author zhouziqiang
 */
@RestController
@Slf4j
@RequestMapping("/admin/workbench")
public class AdminWorkbenchController extends BaseController {
    @Autowired
    private GsResIntentionService gsResIntentionService;
    @Autowired
    private GsOrderService gsOrderService;
    @Autowired
    private GsResService gsResService;
    @Autowired
    private SsoService ssoService;
    @Autowired
    private UserQueryApi userQueryApi;
    @Autowired
    private GsAppIpApplyService gsAppIpApplyService;

    @GetMapping("/getDeptList")
    public Response getDeptList(Integer deptId, String keyWord) throws UnsupportedEncodingException {
        // 查所有部门列表
        if (StringUtil.isNotEmpty(keyWord) && StringUtil.isNotBlank(keyWord)) {
            String param = DeCodeUtil.decodeParam(keyWord);
            return Response.success(userQueryApi.listDept(param));
        } else {
            return Response.success(userQueryApi.listDept(deptId));
        }
    }


    ///////////////////////////////////// IP修改申请单 /////////////////////////////////////


    /**
     * IP修改申请单审批模块
     *
     * @param map (Integer result, String remark, String ipApplyNo)
     * @return
     */
    @PostMapping("/ipApprove")
    public Response ipApplyApprove(@RequestBody HashMap<String, Object> map, HttpServletRequest request) throws Exception {
        UserInfo userInfo = ssoService.getUserInfo(request);
        Assert.isNull(userInfo, "未登录");
        gsAppIpApplyService.ipApprove(userInfo.getUserId(), (Integer) map.get("result"), (String) map.get("remark"), (String) map.get("ipApplyNo"));
        return Response.success();
    }

    /**
     * 管理员查看需要审核的IP修改申请单列表
     *
     * @param request
     * @param page
     * @param appName 自建系统名称 模糊查询
     * @param ip      IP 模糊查询
     * @param state   订单状态
     * @return
     */
    @GetMapping("/getManagerApproveIpApplyPageList")
    public Response getUserIpApplyPageList(HttpServletRequest request, Page page, String appName, String ip, Integer state) throws BizException, UnsupportedEncodingException {
        UserInfo userInfo = ssoService.getUserInfo(request);
        Assert.isNull(userInfo, "未登录");
        appName = URLDecoder.decode(appName, "UTF-8");
        IPage<IpApplyListVo> userApplyList = gsAppIpApplyService.getManagerApproveIpApplyList(userInfo.getUserId(), page.getSize(), page.getCurrent(), appName, ip, state);
        return Response.success(userApplyList);
    }


    ///////////////////////////////////// 用户意向 /////////////////////////////////////

    /**
     * 用户意向单条数据
     */
    @GetMapping("/getIntention")
    public Response getIntention(HttpServletRequest request, Integer id) throws BizException {
        return Response.success(gsResIntentionService.getIntention(id));
    }

    /**
     * 用户意向分页数据
     */
    @GetMapping("/pageIntention")
    public Response pageIntention(HttpServletRequest request, Page<GsResIntention> page, String userName, String contact) throws UnsupportedEncodingException {
        String state = request.getParameter("state");
        if (null != userName) {
            userName = URLDecoder.decode(userName, "UTF-8");
        }
        IPage<ResIntentionVO> result = gsResIntentionService.pageIntention(
                page,
                userName,
                contact,
                StringUtil.isBlank(state) ? null : Integer.valueOf(state)
        );
        return Response.success(result);
    }

    /**
     * 意向备注
     */
    @PostMapping("/remarkIntention")
    public Response remarkIntention(HttpServletRequest request, @RequestBody GsResIntentionRemark remark) throws BizException {
        Assert.isNull(remark.getIntentionId(), "id不能为空");
        Integer userId = ssoService.getUserId(request);
        Assert.isNull(userId, "用户未登录");
        Assert.isBlank(remark.getContent(), "备注内容不能未空");
        gsResIntentionService.remarkIntention(
                remark.getIntentionId(),
                remark.getContent(),
                remark.getFileObjList(),
                userId);
        return Response.success();
    }

    /**
     * 完成沟通
     */
    @PostMapping("/doneIntention")
    public Response doneIntention(HttpServletRequest request, @RequestBody ResIntentionVO intention) throws BizException {
        Assert.isNull(intention.getId(), "id不能为空");
        gsResIntentionService.doneIntention(
                intention.getId(),
                ssoService.getUserInfo(request).getUserId());
        return Response.success();
    }


    ///////////////////////////////////// 需求申请 /////////////////////////////////////

    /**
     * 用户订单分页数据
     */
    @GetMapping("/pageOrder")
    public Response pageOrder(HttpServletRequest request, Page<GsOrderItem> page, String resName, Integer orderState) throws UnsupportedEncodingException {
        String state = request.getParameter("state");
        String key = request.getParameter("orderNo");
        resName = URLDecoder.decode(resName, "UTF-8");
        IPage<ResOrderPgVO> result = gsOrderService.pageOrder(
                page,
                key,
                resName,
                StringUtil.isBlank(state) ? null : Integer.valueOf(state),
                null,
                ssoService.getUserId(request),
                orderState
        );
        return Response.success(result);
    }

    /**
     * 审核用户需求
     */
    @PostMapping("/approve")
    public Response approve(HttpServletRequest request, @RequestBody ApproveFlowParam param) throws Exception {
        Integer userId = ssoService.getUserId(request);
        Assert.isNull(userId, "用户未登录");
        GsApproveFlow gs = new GsApproveFlow();
        gs.setApplyId(param.getApplyId());
        gs.setFileObjList(param.getFileObjList());
        gs.setResult(param.getResult());
        gs.setRemark(param.getRemark());
        gsOrderService.approve(gs, userId, param.getOrderNo());
        return Response.success();
    }


    /**
     * 用户订单详情数据
     */
    @GetMapping("/getOrderDetail")
    public Response getOrderDetail(HttpServletRequest request, String orderNo, Integer itemId) throws BizException {
        UserInfo userInfo = ssoService.getUserInfo(request);
        Assert.isNull(userInfo, "用户未登录");
        ResOrderDetailVO result = gsOrderService.getOrderDetail(orderNo, itemId, userInfo.getUserId());
        return Response.success(result);
    }


    ///////////////////////////////////// 应用管理 /////////////////////////////////////

    /**
     * 应用分页数据
     */
    @GetMapping("/pageRes")
    public Response pageRes(HttpServletRequest request, Page<GsRes> page) {
        IPage<ResSimpleVO> result = gsResService.pageRes(page);
        return Response.success(result);
    }

    /**
     * 单条应用数据
     */
    @GetMapping("/getRes")
    public Response getRes(HttpServletRequest request, Integer id) throws BizException {
        GsRes res = gsResService.getRes(id);
        return Response.success(res);
    }

    /**
     * 创建应用
     */
    @PostMapping("/createRes")
    public Response createRes(@RequestBody GsRes res) throws Exception {
        gsResService.createRes(res);
        return Response.success();
    }

    /**
     * 修改应用
     */
    @PostMapping("/updateRes")
    public Response updateRes(@RequestBody GsRes res) throws Exception {
        gsResService.updateRes(res);
        return Response.success();
    }

    /**
     * 上架应用
     */
    @PostMapping("/putOnRes")
    public Response putOnRes(@RequestBody GsRes res) {
        gsResService.putOnRes(res.getId());
        return Response.success();
    }

    /**
     * 下架应用
     */
    @PostMapping("/putOffRes")
    public Response putOffRes(@RequestBody GsRes res) {
        gsResService.putOffRes(res.getId());
        return Response.success();
    }

    /**
     * 删除应用
     */
    @PostMapping("/removeRes")
    public Response removeRes(@RequestBody GsRes res) throws BizException {
        gsResService.removeRes(res.getId());
        return Response.success();
    }

    /**
     * 应用审核流程所需数据
     */
    @GetMapping("/res/dataMap")
    public Response resDataMap() {
        Map<String, Object> result = new HashMap<>();
        result.put("roleList", userQueryApi.listRole());
        return Response.success(result);
    }

    /**
     * 部门书
     */
    @GetMapping("/res/deptList")
    public Response resDeptList(Integer parentId) {
        return Response.success(userQueryApi.listDept(parentId));
    }
}
